"use strict";
const canvas = document.querySelector("#myCanvas");
const ctx = canvas.getContext("2d");
class rect {
    width;
    height;
    x;
    y;
    color = "black";
    speed;
    constructor(width, height, x, y, color, speed) {
        this.width = width;
        this.height = height;
        this.x = x;
        this.y = y;
        this.color = color;
        this.speed = speed;
    }
    draw() {
        ctx.beginPath();
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.width, this.height);
        ctx.closePath();
    }
    move() {
        this.x += this.speed;
        // 边界检测
        if (this.x > canvas.width - this.width) {
            this.speed *= -1;
        }
        else if (this.x < 0) {
            this.speed *= -1;
        }
        // console.log(this.x, this.speed);
    }
}
const rect1 = new rect(100, 100, 0, 300, "red", 1);
const rect2 = new rect(100, 100, 500, 300, "blue", 2);
// https://zhuanlan.zhihu.com/p/614600309  参考矩形碰撞和包含检测算法
function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    rect1.draw();
    rect1.move();
    rect2.draw();
    rect2.move();
    if (isHit(rect1, rect2)) {
        rect1.speed *= -1;
        rect2.speed *= -1;
    }
    requestAnimationFrame(animate);
}
function isHit(r1, r2) {
    return (rect1.x <= rect2.x + rect2.width &&
        rect1.x + rect1.width >= rect2.x &&
        rect1.y <= rect2.y + rect2.height &&
        rect1.y + rect1.height >= rect2.y);
}
animate();
